﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using MiniX.API.Data;
using Serilog;
using Microsoft.Extensions.Configuration;
using System.IO;
using Serilog.Core;
using MiniX.Utility.Authorization;
using Microsoft.AspNetCore.Http.Extensions;
using MiniX.Models;
using Senparc.CO2NET.Extensions;
using System.Security.Claims;
using Microsoft.CodeAnalysis;
using Serilog.Context;

namespace MiniX.API.Controllers
{
    /// <summary>
    /// 基类，封装了TOKEN、日志相关操作
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseController<T> : Controller
    {
        /// <summary>
        /// _context
        /// </summary>
        protected readonly MiniXApiContext _context;
        /// <summary>
        /// Log变量
        /// </summary>
        public Logger log;
        /// <summary>
        /// _httpContextAccessor
        /// </summary>
        private readonly IHttpContextAccessor _httpContextAccessor;
        /// <summary>
        /// 全局会员ID（高并发时会员信息会错乱还没有得到可靠验证，暂时不要用此参数，意味着前端每个接口必须传参会员ID）
        /// </summary>
        public string MEMBER_ID => HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)!.Value;

        /// <summary>
        /// 构造基类方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="httpContextAccessor"></param>
        public BaseController(MiniXApiContext context, IHttpContextAccessor httpContextAccessor)
        {
            _context = context;
            _httpContextAccessor = httpContextAccessor;

            // 初始化日志
            log = new LoggerConfiguration()
             .ReadFrom.Configuration(new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
             .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
             .Build())
             .CreateLogger();
        }
    }
}
